<template>
  <div class="user-list-container">
    <!-- 查询表单 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="搜索" prop="username">
              <el-input placeholder="搜索商品名称" v-model="queryParams.search" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品分类" prop="goods_cate_id">
              <el-select v-model="queryParams.goods_cate_id" placeholder="请选择分类" clearable>
                <el-option v-for="item in statusOptions" :key="item.goods_cate_id" :label="item.goods_cate_name"
                  :value="item.goods_cate_id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否上架" prop="is_up">
              <el-select v-model="queryParams.is_up" placeholder="请选择上架状态" clearable>
                <el-option v-for="item in statusup" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: right">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card shadow="never" class="table-card">
      <div style="display: flex; margin-bottom: 20px">
        <el-button type="primary" @click="openAddDialog">创建商品</el-button>
      </div>
      <el-table v-loading="loading" class="table" :data="tableData" border style="width: 100%">
        <el-table-column prop="goods_id" label="ID" width="80" fixed />
        <el-table-column prop="goods_name" label="商品名称" />
        <el-table-column prop="goods_cover_path" label="商品封面图">
          <template #default="scope">
            <el-image v-if="scope.row.goods_cover_path" :src="scope.row.goods_cover_path"
              style="width: 60px; height: 60px" :preview-src-list="[scope.row.goods_cover_path]" hide-on-click-modal
              preview-teleported />
          </template>
        </el-table-column>
        <el-table-column prop="goods_cate_name" label="分类名称" />
        <el-table-column prop="goods_describe" label="商品描述" width="200" />
        <el-table-column prop="goods_price" label="商品价格" />
        <el-table-column label="是否上架" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.is_up" :active-value="1" :inactive-value="0"
              @change="handleStatusChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="添加时间" width="200" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button link @click="handleEdit(scope.row)">编辑</el-button>
            <!-- <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="page" :page-sizes="[10, 20, 30, 50]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" />
    </el-card>

    <!-- 商品编辑/创建对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'edit' ? '编辑商品' : '创建商品'" width="1000px"
      :before-close="handleCloseAddDialog">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="150px" class="demo-form">
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="form.goods_name" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="商品分类" prop="goods_cate_id">
          <el-select v-model="form.goods_cate_id" placeholder="请选择分类" clearable style="width: 100%">
            <el-option v-for="item in statusOptions" :key="item.goods_cate_id" :label="item.goods_cate_name"
              :value="item.goods_cate_id" />
          </el-select>
        </el-form-item>

        <el-form-item label="商品封面图" prop="goods_cover_path">
          <upload :key="`cover-upload-${dialogVisible}`" :img-file="form.goods_cover_path" :limit="1"
            @change="(val) => { form.goods_cover_path = val }" />
          <div class="el-form-item-msg">建议尺寸：300*300px</div>
        </el-form-item>
        <el-form-item label="商品轮播图" prop="goods_banner">
          <el-upload action="https://shalong.taiyanyue.top/api/common/OSSFileUpload" list-type="picture-card"
            :file-list="bannerFileList" :on-success="handleBannerSuccess" :on-remove="handleBannerRemove"
            :before-upload="beforeBannerUpload" :limit="5" multiple :on-exceed="handleBannerExceed">
            <el-icon>
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">最多上传5张，建议尺寸：750*750px</div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品描述" prop="goods_describe">
          <el-input v-model="form.goods_describe" type="textarea" :rows="3" placeholder="请输入商品描述" />
        </el-form-item>

        <el-form-item label="商品价格" prop="goods_price">
          <el-input-number v-model="form.goods_price" :min="0" :precision="2" :controls="false" placeholder="请输入商品价格"
            style="width: 100%" />
        </el-form-item>

        <el-form-item label="是否上架" prop="is_up">
          <el-switch v-model="form.is_up" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="商品详情" prop="goods_e">
          <rich-txt :modelValue="form.goods_e" @change="(val) => { form.goods_e = val }"></rich-txt>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAddDialog">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import tableMixin from "@/mixins/tableMixin";
import api from "@/request/api.js";
import upload from "@/components/upload.vue";
import richTxt from "@/components/richTxt.vue";
import { Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

export default {
  name: "GoodsList",
  mixins: [tableMixin],
  components: { upload, richTxt, Plus },
  data() {
    return {
      //查询参数
      queryParams: {
        search: '',
        goods_cate_id: null,
        is_up: null
      },
      apimodel: "spjifengood",
      apival: "orderList",
      // 状态选项
      statusOptions: [],
      statusup: [
        { value: 1, label: "是" },
        { value: 0, label: "否" }
      ],
      // 创建修改弹窗
      dialogVisible: false,
      dialogType: "",
      form: {
        goods_name: "",
        goods_cate_id: null,
        goods_cover_path: "",
        goods_banner: [],
        goods_describe: "",
        goods_price: 0,
        is_up: 1,
        goods_e: ""
      },
      bannerFileList: [], // 轮播图文件列表
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_cate_id: [
          { required: true, message: "请选择商品分类", trigger: "change" }
        ],
        goods_cover_path: [
          { required: true, message: "请上传商品封面图", trigger: "change" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ]
      }
    };
  },
  mounted() {
    // 获取分类列表
    api.goodscaclass.getList({ size: 999 }).then((res) => {
      if (res.data.code == 200) {
        this.statusOptions = res.data.content.data;
      }
    });
  },
  methods: {
    // 状态切换
    handleStatusChange(row) {
      api.spjifengood
        .updateStatus({
          goods_id: row.goods_id,
          is_up: row.is_up
        })
        .then((res) => {
          if (res?.status == 200) {
            this.$message.success("状态修改成功");
            this.getTableData();
          } else {
            // 恢复之前的状态
            row.is_up = row.is_up == 1 ? 0 : 1;
          }
        })
        .catch(() => {
          // 恢复之前的状态
          row.is_up = row.is_up == 1 ? 0 : 1;
        });
    },

    // 打开创建对话框
    openAddDialog() {
      this.dialogVisible = true;
      this.dialogType = "add";
      // 重置表单验证状态
      this.$nextTick(() => {
        this.resetForm();
      });
      // 重置表单数据
      this.form = {
        goods_name: "",
        goods_cate_id: null,
        goods_cover_path: "",
        goods_banner: [],
        goods_describe: "",
        goods_price: 0,
        is_up: 1,
        goods_e: ""
      };
      this.bannerFileList = [];
    },

    // 编辑商品
    handleEdit(row) {
      this.$nextTick(() => {
        this.resetForm();
      });
      // 重置表单数据
      this.form = {
        goods_name: "",
        goods_cate_id: null,
        goods_cover_path: "",
        goods_banner: [],
        goods_describe: "",
        goods_price: 0,
        is_up: 1,
        goods_e: ""
      };
      this.bannerFileList = [];
      api.spjifengood.ckxq({ goods_id: row.goods_id }).then((res) => {
        if (res.data.code == 200) {
          const data = res.data.content.data;

          // 处理轮播图数据
          this.bannerFileList = data.goods_banner_arr
            ? data.goods_banner_arr.map(item => ({
              url: item.goods_banner_path
            }))
            : [];

          this.form = {
            ...data,
            goods_cover_path: data.goods_cover_path || '',
            goods_banner: data.goods_banner_arr
              ? data.goods_banner_arr.map(item => item.goods_banner_path)
              : [],
            goods_e: data.goods_e || ''
          };

          this.dialogType = "edit";
          this.dialogVisible = true;
        }
      });
    },

    // 关闭对话框
    handleCloseAddDialog() {
      this.dialogVisible = false;
      this.dialogType = "";
      // 重置表单验证状态
      this.$nextTick(() => {
        this.resetForm();
      });
      // 重置表单数据
      this.form = {
        goods_name: "",
        goods_id: null,
        goods_cover_path: "",
        goods_banner: [],
        goods_describe: "",
        goods_price: 0,
        is_up: 1,
        goods_e: ""
      };
      this.bannerFileList = [];
    },

    // 轮播图上传成功处理
    handleBannerSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.form.goods_banner.push(response.content.path);
        this.bannerFileList = fileList.map(item => {
          if (item.response) {
            return { url: item.response.content.path };
          }
          return item;
        });
      } else {
        ElMessage.error('上传失败: ' + (response.message || '未知错误'));
      }
    },

    // 轮播图移除处理
    handleBannerRemove(file, fileList) {
      // 从form.goods_banner中移除对应的图片
      const url = file.url || (file.response && file.response.data.url);
      if (url) {
        this.form.goods_banner = this.form.goods_banner.filter(item => item !== url);
      }
      this.bannerFileList = fileList;
    },

    // 轮播图上传前校验
    beforeBannerUpload(file) {
      const isImage = file.type.includes('image/');
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        ElMessage.error('只能上传图片文件!');
      }
      if (!isLt5M) {
        ElMessage.error('图片大小不能超过5MB!');
      }

      return isImage && isLt5M;
    },

    // 轮播图超出限制处理
    handleBannerExceed(files, fileList) {
      ElMessage.warning(`最多只能上传5张轮播图，当前选择了${files.length}张，共${files.length + fileList.length}张`);
    },

    // 提交表单
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 确保轮播图数据是数组格式
          const goodsBannerArr = Array.isArray(this.form.goods_banner)
            ? [...this.form.goods_banner].map((path, index) => ({
              goods_banner_path: path,
              goods_sort: index + 1
            }))
            : [];

          const submitData = {
            goods_name: this.form.goods_name,
            goods_cover_path: this.form.goods_cover_path || '',
            goods_cate_id: this.form.goods_cate_id,
            goods_describe: this.form.goods_describe,
            goods_price: this.form.goods_price,
            goods_e: this.form.goods_e,
            is_up: this.form.is_up,
            goods_banner_arr: goodsBannerArr
          };

          if (this.dialogType === "edit") {
            submitData.goods_id = this.form.goods_id;
            api.spjifengood.updates(submitData).then((res) => {
              if (res?.status == 200) {
                this.$message.success("修改成功");
                this.handleReset();
                this.handleCloseAddDialog();
              }
            });
          } else {
            api.spjifengood.creates(submitData).then((res) => {
              if (res?.status == 200) {
                this.$message.success("创建成功");
                this.handleReset();
                this.handleCloseAddDialog();
              }
            });
          }
        }
      });
    },

    // 删除商品
    handleDelete(row) {
      this.$confirm("确认删除该商品吗?", "提示", {
        type: "warning",
      })
        .then(async () => {
          api.spjifengood
            .del({
              goods_id: row.goods_id,
            })
            .then((res) => {
              if (res?.status == 200) {
                this.$message.success("删除成功");
                this.getTableData();
              }
            });
        })
        .catch(() => { });
    },

    resetForm() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
        // 清除上传组件的显示（因为resetFields不会清除上传组件）
        if (this.$refs.uploadRef) {
          this.$refs.uploadRef.clearFiles();
        }
      }
    },
  }
};
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.el-form-item-msg {
  font-size: 12px;
  color: #999;
  line-height: 1.5;
  margin-top: 5px;
}

/* 调整上传组件样式 */
:deep(.el-upload--picture-card) {
  width: 80px;
  height: 80px;
  line-height: 80px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 80px;
  height: 80px;
}
</style>